# encoding:utf-8

import os
import re

from baidu_ocr import analyze_local_image
from bean_task import BeanTask
from utils.screen_snapshot import get_snapshot


def get_time_bean_count(result):
    key = "我的翻倍豆"

    to_invent = list(filter(lambda x: key in x['words'], result['words_result']))
    return re.findall("我的翻倍豆([0-9]+).*", to_invent[0]['words'])[0] if len(to_invent) == 1 else None


def calculate_income(start_image_path, end_image_path):
    start_content = analyze_local_image(start_image_path, re.sub(".png", ".json", start_image_path))
    end_content = analyze_local_image(end_image_path, re.sub(".png", ".json", end_image_path))
    start_income = int(get_time_bean_count(start_content))
    end_income = int(get_time_bean_count(end_content))
    return end_income - start_income


def extract_task(word_results):
    tasks = []
    STEP_TO_SCORE = 1

    start_index = None
    for inx, val in enumerate(word_results):
        # print(val['words'])
        if re.match("^翻倍豆\+[0-9]+$", val['words']):
            print("{} : {}".format(inx, val['words']))
            start_index = inx - STEP_TO_SCORE
            break

    if not start_index:
        raise Exception("没有找到任务开始标识")

    print("start index = {}".format(start_index))

    task_item_number = []
    for inx, val in enumerate(word_results):
        if val['words'] in ['去邀请', '领任务', '去完成', '已完成']:
            print("{} : {}".format(inx, val['words']))
            task_item_number.append(inx)

    print(task_item_number)

    if len(task_item_number) == 0:
        raise Exception("分割任务失败")

    item_size_list = [task_item_number[i + 1] - task_item_number[i] for i in range(len(task_item_number) - 1)]
    item_size_list.insert(0, task_item_number[0] - start_index + 1)

    print(item_size_list)
    total_task_item = len(item_size_list)

    for i in range(0, total_task_item):
        block_start_index = start_index + i
        block_end_index = block_start_index + item_size_list[i]
        if item_size_list[i] == 5:
            [title, description, flag, score, action] = word_results[block_start_index:block_end_index]
        else:
            [title, description, score, action] = word_results[block_start_index:block_end_index]
        tasks.append(BeanTask(title, description, score, action))
    return tasks

def action_match(action):
    for i in ['逛一逛','看','逛','浏览','']:
        if i in action:
            matched = True
            break
    return matched or False

def earn_first_task_score(tasks):
    for t in tasks:
        if t.action['words'] == '去完成' and action_match(t.title['words']):
            pass


if __name__ == "__main__":
    # file_path = 'a.json'
    # content = analyze_local_image('2019-12-29_18_59_56-start.png', '2019-12-29_18_59_56-start.json')
    # # print(content)
    # bean_count = get_time_bean_count(content)
    # print(bean_count)
    # print(re.findall("我的翻倍豆([0-9]+)个", "我的翻倍豆1078988个")[0])
    if 2 == 1:
        income = calculate_income(r'E:\codepiece\junp-4-double-twelve\2019-12-29_18_59_56-start.png',
                                  r'E:\codepiece\junp-4-double-twelve\2019-12-29_18_59_56-end.png')
        print("income = {} on {}".format(income, '2019-12-29_18_59_56'))

    task_list_image_path = 'task_list.png'
    task_list_json_path = 'task_list.json'

    if not os.path.exists(task_list_image_path):
        get_snapshot(task_list_image_path)

    content = analyze_local_image(task_list_image_path, task_list_json_path)

    tasks = extract_task(content['words_result'])

    print(tasks)
    print(len(tasks))

    earn_first_task_score(tasks)
